package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.example.entity.AjaxResult;
import org.example.entity.LoginVO;
import org.example.entity.Token;
import org.example.service.impl.TokenService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
public class LoginController {
    private final TokenService tokenService;

//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody LoginVO loginVO){
//        Token token=tokenService.createToken(loginVO);
//        return AjaxResult.ok(token);
//    }
//登陆
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginVO){
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVO.getLoginName(),loginVO.getPassword());
        try {
            Token token=tokenService.createToken(loginVO);
            SecurityUtils.getSubject().login(usernamePasswordToken);
        }catch (UnknownAccountException ex){
            return AjaxResult.err("用户不存在");
        }catch (AuthenticationException ex){
            return AjaxResult.err("用户名或密码错误");
        }
        return AjaxResult.ok();
    }
    @GetMapping("/logout")
    public AjaxResult logout(@RequestHeader String token){
        tokenService.removeToken(token);
        return AjaxResult.ok();
    }
}
